from ecdsa import SigningKey, NIST384p
from hashlib import sha256

# 生成密钥对
def generate_keypair():
    sk = SigningKey.generate(curve=NIST384p)  # 生成私钥
    vk = sk.get_verifying_key()  # 生成公钥
    return sk, vk

# 加密消息
def encrypt_message(vk, message):
    # 将消息转换为字节
    message_bytes = message.encode('utf-8')
    # 使用公钥进行加密
    encrypted_message = vk.encrypt(message_bytes, hashfunc=sha256)
    return encrypted_message

# 解密消息
def decrypt_message(sk, encrypted_message):
    # 使用私钥进行解密
    decrypted_message = sk.decrypt(encrypted_message, hashfunc=sha256)
    # 将字节转换回字符串
    return decrypted_message.decode('utf-8')

# 主函数
if __name__ == "__main__":
    # 生成密钥对
    sk, vk = generate_keypair()
    print(f"Private Key: {sk.to_string().hex()}")
    print(f"Public Key: {vk.to_string().hex()}")
    # 明文消息
    message = "Hello, ECC!"

    # 加密消息
    encrypted_message = encrypt_message(vk, message)
    print(f"Encrypted Message: {encrypted_message}")

    # 解密消息
    decrypted_message = decrypt_message(sk, encrypted_message)
    print(f"Decrypted Message: {decrypted_message}")